package com.netty.action.dischard;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Arrays;

public class DiscardServerHandler extends SimpleChannelInboundHandler<Object> {

    /**
     * 这里接收了客户端发来的数据，并没有dischard(丢弃)
     * 主要是为了体验收到的数据
     * 注意客户端发来的是directbuf 全是0的数据，客户端就是一直不断发0
     * 具体可以查看DiscardClientHandler
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        if(!in.hasArray()){
            int length = in.readableBytes();
            byte [] array =  new byte[length];
            in.getBytes(in.readerIndex(),array);
            System.out.println("Server received: " + Arrays.toString(array));
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}